<?php
require_once __DIR__ . '/../vendor/autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Exchange\AMQPExchangeType;

$config = [
    'host' => '127.0.0.1',
    'vhost' => '/',
    'port' => 5672,
    'login' => 'guest',
    'password' => 'guest',
];

//交换器名称
$exchange = 'routing';
try {
    //建立连接到RabbitMQ服务器
    $connection = new AMQPStreamConnection($config['host'], $config['port'], $config['login'], $config['password'], $config['vhost']);
    //建立通道
    $channel = $connection->channel();
    //试探性声明一个交换机
    $channel->exchange_declare($exchange, AMQPExchangeType::DIRECT, false, true, false);
    //获取routing_key,没有默认为'info'
    $routingKey = isset($argv[1]) && !empty($argv[1]) ? $argv[1] : 'info';
    //获取发送数据
    $messageBody = array_slice($argv, 2);
    //没有传入消息提示错误
    if (empty($messageBody)) throw new Exception('请输入消息');
    //定义消息
    $message = new AMQPMessage($messageBody, ['content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]);
    //生产消息
    $channel->basic_publish($message, $exchange, $routingKey);
    $channel->close();// 关闭通道
    $connection->close();// 关闭连接
} catch (Exception $e) {
    die($e->getMessage());
}